package com.cy.aircompressor.main.home.dialog;

import android.os.Bundle;
import android.text.TextUtils;

import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Observer;

import com.blankj.utilcode.util.TimeUtils;
import com.cy.aircompressor.databinding.DialogLineChartFull2Binding;
import com.cy.aircompressor.entity.linechart.LineChartEntry;
import com.cy.aircompressor.entity.sensor.SensorBgg;
import com.cy.aircompressor.entity.sensor.SensorItemData;
import com.cy.aircompressor.entity.sensor.SensorLineChartData;
import com.cy.aircompressor.entity.sensor.SensorLatestData;
import com.cy.aircompressor.entity.sensor.SensorStatisticsData;
import com.cy.aircompressor.main.home.viewmodel.MainContentViewModel;
import com.cy.aircompressor.main.ui.onlinemonitor.utils.LineChartUtil;
import com.drug.lib.util.DLog;
import com.github.mikephil.charting.data.Entry;
import com.jakewharton.rxbinding2.view.RxView;
import com.net.model.base.Resource;
import com.net.model.base.fragment.BaseVMDialogFragment;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class LineChartFullScreenDialogV2 extends BaseVMDialogFragment<DialogLineChartFull2Binding, MainContentViewModel> {
    SensorLineChartData sensorLineChartData;

    public static void showDialogFragment(FragmentManager fragmentManager, String tag, SensorLineChartData sensorLineChartData) {
        if (sensorLineChartData == null) return;

        Bundle args = new Bundle();
        LineChartFullScreenDialogV2 fragment = new LineChartFullScreenDialogV2();
        args.putSerializable("sensorLineChartData", sensorLineChartData);
        fragment.setArguments(args);
        fragment.show(fragmentManager, tag);
    }

    @Override
    protected DialogLineChartFull2Binding getViewBinding() {
        return DialogLineChartFull2Binding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {
        sensorLineChartData = (SensorLineChartData) getArguments().getSerializable("sensorLineChartData");
        initView();
        setRealTimeData(sensorLineChartData.getSensorLatestData());
        loadLineChart();
    }

    @Override
    protected void requestNetwork() {
        getHandler().postDelayed(loadSensorDataRunnable, 60 * 1000);
    }

    @Override
    protected int getWindowHeight() {
        return getScreenHeight() * 2 / 3;
    }

    @Override
    protected int getWindowWidth() {
        return getScreenWidth() * 2 / 3;
    }

    @Override
    protected void dataChange() {

        mViewModel.getQueryCompressorSensorDataObservable().observe(this, new Observer<Resource<List<SensorLatestData>>>() {
            @Override
            public void onChanged(Resource<List<SensorLatestData>> sensorDataResource) {
                sensorDataResource.handler(new OnCallback<List<SensorLatestData>>() {
                    @Override
                    public void onSuccess(List<SensorLatestData> data) {
                        if (data == null) return;
                        SensorLatestData sensorLatestData = getSensorRealTimeData(sensorLineChartData.getSensorLatestData().getCompressorId(), data);
                        sensorLineChartData.setSensorLatestData(sensorLatestData);
                        setRealTimeData(sensorLatestData);

                    }
                });
            }
        });


        mViewModel.getQuerySensorStatisticsDataDataObservable().observe(this, new Observer<Resource<List<SensorStatisticsData>>>() {
            @Override
            public void onChanged(Resource<List<SensorStatisticsData>> listResource) {
                listResource.handler(new OnCallback<List<SensorStatisticsData>>() {
                    @Override
                    public void onSuccess(List<SensorStatisticsData> data) {
                        sensorLineChartData.getSensorBgg().setSensorStatisticsData(data);
                        loadLineChart();
                    }
                });
            }
        });
    }


    /**
     * 初始化view设置
     */
    private void initView() {
        LineChartUtil.initLineChart(mBinding.lineChart, true);
        switch (sensorLineChartData.getPointCode()) {
            case "vibration1":
                mBinding.titleName.setText("机身震动变化趋势");
                break;
            case "vibration2":
                mBinding.titleName.setText("一级气缸震动变化趋势");
                break;
            case "vibration3":
                mBinding.titleName.setText("二三级气缸震动变化趋势");
                break;
        }
        mBinding.switchBtn.setText(sensorLineChartData.isSpeed() ? "切换speed曲线" : "切换rms曲线");

        RxView.clicks(mBinding.fullScreen)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    dismiss();
                });
        RxView.clicks(mBinding.switchBtn)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    sensorLineChartData.setSpeed(!sensorLineChartData.isSpeed());
                    mBinding.switchBtn.setText(sensorLineChartData.isSpeed() ? "切换speed曲线" : "切换rms曲线");
                    setRealTimeData(sensorLineChartData.getSensorLatestData());
                    loadLineChart();
                });
    }

    /**
     * 设置最新数据
     *
     * @param sensorLatestData
     */
    private void setRealTimeData(SensorLatestData sensorLatestData) {
        if (sensorLatestData == null) {
            mBinding.xValue.setText("-");
            mBinding.yValue.setText("-");
            mBinding.zValue.setText("-");
        } else {
            SensorItemData sensorItemData = getSensorItemData("body", sensorLineChartData.getPointCode(), sensorLatestData.getDataList());
            if (sensorItemData == null) {
                mBinding.xValue.setText("-");
                mBinding.yValue.setText("-");
                mBinding.zValue.setText("-");
                return;
            }
            double Xspeed = sensorItemData.getXspeed();
            double Yspeed = sensorItemData.getYspeed();
            double Zspeed = sensorItemData.getZspeed();

            double Xrms = sensorItemData.getXrms();
            double Yrms = sensorItemData.getYrms();
            double Zrms = sensorItemData.getZrms();

            mBinding.xValue.setText(String.valueOf(sensorLineChartData.isSpeed() ? Xspeed : Xrms));
            mBinding.yValue.setText(String.valueOf(sensorLineChartData.isSpeed() ? Yspeed : Yrms));
            mBinding.zValue.setText(String.valueOf(sensorLineChartData.isSpeed() ? Zspeed : Zrms));
        }
    }

    private void loadLineChart() {
        SensorBgg sensorBgg = sensorLineChartData.getSensorBgg();
        if (sensorBgg != null) {
            List<SensorStatisticsData> sensorStatisticsData = sensorBgg.getSensorStatisticsData();
            if (sensorStatisticsData != null && sensorStatisticsData.size() != 0) {
                stowageData(sensorBgg, sensorLineChartData.isSpeed());
            } else {
                LineChartUtil.addEmptyLine(mBinding.lineChart);
            }
        } else {
            LineChartUtil.addEmptyLine(mBinding.lineChart);
        }
        LineChartUtil.checkLineChart(mBinding.lineChart);
    }

    private void stowageData(SensorBgg sensorBgg, boolean isSpeed) {
        List<Entry> entrieX = new ArrayList<>();
        List<Entry> entrieY = new ArrayList<>();
        List<Entry> entrieZ = new ArrayList<>();
        List<SensorStatisticsData> sensorStatisticsData = sensorBgg.getSensorStatisticsData();
        for (SensorStatisticsData statisticsData : sensorStatisticsData) {
            Date date = null;
            try {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                date = format.parse(statisticsData.getRt());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (isSpeed) {
                Entry entry = new Entry(sensorStatisticsData.indexOf(statisticsData), statisticsData.getXspeed(), date.getTime());
                entrieX.add(entry);

                entry = new Entry(sensorStatisticsData.indexOf(statisticsData), statisticsData.getYspeed(), date.getTime());
                entrieY.add(entry);

                entry = new Entry(sensorStatisticsData.indexOf(statisticsData), statisticsData.getZspeed(), date.getTime());
                entrieZ.add(entry);

            } else {
                Entry entry = new Entry(sensorStatisticsData.indexOf(statisticsData), statisticsData.getXrms(), date.getTime());
                entrieX.add(entry);

                entry = new Entry(sensorStatisticsData.indexOf(statisticsData), statisticsData.getYrms(), date.getTime());
                entrieY.add(entry);

                entry = new Entry(sensorStatisticsData.indexOf(statisticsData), statisticsData.getZrms(), date.getTime());
                entrieZ.add(entry);

            }
        }
        LineChartEntry xLineChartEntry = sensorBgg.getxLineChartEntry();
        xLineChartEntry.setEntrys(entrieX);
        xLineChartEntry.setColor(getColor("x"));
        LineChartEntry yLineChartEntry = sensorBgg.getyLineChartEntry();
        yLineChartEntry.setEntrys(entrieY);
        yLineChartEntry.setColor(getColor("y"));
        LineChartEntry zLineChartEntry = sensorBgg.getzLineChartEntry();
        zLineChartEntry.setEntrys(entrieZ);
        zLineChartEntry.setColor(getColor("z"));

        List<LineChartEntry> lineChartEntries = new ArrayList<>();
        lineChartEntries.add(xLineChartEntry);
        lineChartEntries.add(yLineChartEntry);
        lineChartEntries.add(zLineChartEntry);
        LineChartUtil.addAndUpdateLine(mBinding.lineChart, lineChartEntries);
    }


    private SensorItemData getSensorItemData(String partCode, String pointCode, List<SensorItemData> dataList) {
        if (dataList == null)
            return null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            List<SensorItemData> sensorItemDataList = dataList.stream()
                    .filter(new Predicate<SensorItemData>() {
                        @Override
                        public boolean test(SensorItemData sensorItemData) {
                            return TextUtils.equals(sensorItemData.getCompressorPartCode(), partCode) &&
                                    TextUtils.equals(sensorItemData.getCompressorPointCode(), pointCode);
                        }
                    }).collect(Collectors.toList());
            if (sensorItemDataList != null && sensorItemDataList.size() > 0) {
                return sensorItemDataList.get(0);
            }
        }
        return null;

    }

    private SensorLatestData getSensorRealTimeData(String compressor, List<SensorLatestData> data) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            List<SensorLatestData> sensorLatestDataList = data.stream()
                    .filter(new Predicate<SensorLatestData>() {
                        @Override
                        public boolean test(SensorLatestData sensorRealTimeData) {
                            return TextUtils.equals(sensorRealTimeData.getCompressorId(), compressor);
                        }
                    }).collect(Collectors.toList());
            if (sensorLatestDataList != null && sensorLatestDataList.size() > 0) {
                return sensorLatestDataList.get(0);
            }
        }
        return null;
    }

    private String getColor(String shaft) {
        switch (shaft) {
            case "x":
                return "#CF931F";
            case "y":
                return "#CF1F5E";
            case "z":
                return "#1F66CF";
            default:
                return "#FFFFFF";
        }
    }

    Runnable loadSensorDataRunnable = new Runnable() {
        @Override
        public void run() {
            queryCompressorNewData();
            loadSensorStatisticsData();
        }
    };

    /**
     * 查询当前空压机最新数据
     */
    private void queryCompressorNewData() {
        if (TextUtils.isEmpty(sensorLineChartData.getCompressorId())) {
            return;
        }
        List<String> list = new ArrayList<>();
        list.add(sensorLineChartData.getCompressorId());
        mViewModel.queryCompressorSensorRealTimeData(list);
    }


    /**
     * 根据传感器获取传感器统计数据
     */
    private void loadSensorStatisticsData() {
        if (sensorLineChartData.getSensorBgg() == null) {
            return;
        }
        DLog.e("------获取空压机最近一小时数据------");
        DLog.e("------空压机安装传感器点位：------" + sensorLineChartData.getSensorBgg().getSensor().getCompressorPointCode());
        long endTime = System.currentTimeMillis();
        long startTime = endTime - (60 * 24 * 60 * 60 * 1000L);
        SensorBgg sensorBgg = sensorLineChartData.getSensorBgg();
        String pattern = "yyyy-MM-dd HH:mm:ss";
        mViewModel.querySensorStatisticsData(TimeUtils.date2String(new Date(startTime), pattern), TimeUtils.date2String(new Date(endTime), pattern), sensorBgg.getSensor().getSn(), Integer.parseInt(sensorBgg.getSensor().getType()));
        getHandler().postDelayed(loadSensorDataRunnable, 60 * 1000);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        getHandler().removeCallbacks(loadSensorDataRunnable);
    }
}
